package com.meizi.user.service.biz;

import com.meizi.core.tool.api.R;
import com.meizi.core.tool.exception.BizException;
import com.meizi.core.tool.utils.JwtGeneratorUtil;
import com.meizi.user.service.bo.AuthLoginBo;
import com.meizi.user.service.mapper.entitys.TbMember;
import com.meizi.user.service.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public abstract class AbstractLogin implements Login {

    public static ConcurrentHashMap<Integer, AbstractLogin> loginMap = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        loginMap.put(getLoginType(), this);
    }

    @Override
    public R doLogin(AuthLoginBo authLoginBo) throws BizException {
        log.info("begin AbstractLogin.doLogin:" + authLoginBo);
        validate(authLoginBo); //第一步完成验证
        TbMember member = doProcessor(authLoginBo);
        Map<String, Object> payLoad = new HashMap<>();
        payLoad.put("uid", member.getId());
        payLoad.put("exp", DateTime.now().plusHours(1).toDate().getTime() / 1000);
        String token = JwtGeneratorUtil.generatorToken(payLoad);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setUserId(member.getId());
        loginVo.setUsername(authLoginBo.getUsername());
        return new R().ofSuccess(loginVo);
    }

    public abstract int getLoginType();

    public abstract void validate(AuthLoginBo authLoginBo);

    public abstract TbMember doProcessor(AuthLoginBo authLoginBo);

}
